package com.smart.manage.utils;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @Author lingyao
 * @Version 1.0
 * @Description
 * @Date 2025/03/07 16:32
 */
public class DeepSeekUtils {
    private static final String API_KEY = "sk-4df5790fb5ba4e8897fa1c230c1f4870";
    private static final String BASE_URL = "https://api.deepseek.com";

    public static String getChat(String prompt) throws Exception {
        // 通过拼接提示词简短AI回答字数
        prompt = prompt + "简短的说明一下，控制在150字以内";

        // 创建用户消息对象，并设置角色和内容
        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", prompt);

        // API 的基础 URL 和完整请求路径
        String url = BASE_URL + "/chat/completions";

        // 创建请求体 JSON 对象，并设置模型名称和消息列表
        JSONObject payload = new JSONObject();
        payload.put("model", "deepseek-chat");

        // 将用户消息添加到消息列表中
        JSONArray messages = new JSONArray();
        messages.add(userMessage);
        payload.put("messages", messages);
        payload.put("max_tokens", 200);

        // 创建 HTTP 客户端和 POST 请求对象
        HttpClient client = HttpClients.createDefault();
        HttpPost postMethod = new HttpPost(url);

        // 设置请求头信息，包括内容类型和授权令牌
        postMethod.setHeader("Content-Type", "application/json");
        postMethod.setHeader("Authorization", "Bearer " + API_KEY);

        // 将请求体转换为字符串实体，并设置到 POST 请求中
        StringEntity entity = new StringEntity(payload.toString(), "UTF-8");
        postMethod.setEntity(entity);

        // 执行 HTTP 请求并获取响应
        HttpResponse response = client.execute(postMethod);

        // 检查响应状态码是否为 200（成功）
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new RuntimeException("HTTP请求失败，状态码：" + statusCode);
        }

        // 解析响应字符串为 JSON 对象
        String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
        JSONObject responseJson = JSONObject.parseObject(responseString);

        // 获取 API 响应中的 choices 数组
        JSONArray choices = responseJson.getJSONArray("choices");

        // 检查 choices 数组是否存在且不为空
        if (choices == null || choices.isEmpty()) {
            throw new RuntimeException("API 响应中缺少 choices 字段或为空");
        }

        // 获取第一个选择项的消息对象
        JSONObject firstChoice = choices.getJSONObject(0);
        JSONObject assistantMessage = firstChoice.getJSONObject("message");

        // 返回助手消息的内容
        return assistantMessage.getString("content");
    }
}
